<template>
  <div class="app-container">

    <!-- 查询条件开始 -->
    <el-row :gutter="12" style="margin-bottom:5px">
      <el-col :span="24">
        <el-card>
          <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="科室名称" prop="deptId">
              <el-select
                  v-model="queryParams.deptId"
                  placeholder="请选择科室名称"
                  clearable
                  size="small"
                  style="width:180px">
                <el-option
                    v-for="d in deptOptions"
                    :key="d.deptId"
                    :label="d.deptName"
                    :value="d.deptId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="医生名称" prop="userId">
              <el-select
                  v-model="queryParams.userId"
                  placeholder="请选择医生名称"
                  clearable
                  size="small"
                  style="width:180px">
                <el-option
                    v-for="d in userOptions"
                    :key="d.userId"
                    :label="d.userName"
                    :value="d.userId"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
            <el-form-item style="float:right">
              <el-button type="primary" icon="el-icon-plus" size="small" @click="upWeek">上一周</el-button>
              <el-button type="success" icon="el-icon-s-operation" size="small" @click="currentWeek">当前周
              </el-button>
              <el-button type="primary" icon="el-icon-plus" size="small" @click="nextWeek">下一周</el-button>
              <el-button type="primary"  size="small" @click="chongzhi">刷新！！！！</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    <!-- 查询条件结束 -->


    <!-- 时间范围开始 -->
    <el-row :gutter="12" style="margin-bottom:5px">
      <el-col :span="24">
        <el-card>
          <div style="text-align:center">
            <span>{{ schedulingData.startTimeThisWeek }}(周一)</span>-<span>{{
              schedulingData.endTimeThisWeek
            }}(周日)</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 时间范围结束 -->


    <!-- 排班表格开始 -->
    <el-table v-loading="loading" :data="tableData" border :span-method="spanMethod" v-if="tableData">
      <el-table-column prop="userId" label="医生" align="center" width="100" :formatter="userFormatter" />
      <el-table-column prop="deptId" label="科室" align="center" width="100" :formatter="deptFormatter"/>
      <el-table-column prop="subsectionType" label="时间/日期" width="100"  align="center"
                       :formatter="subsectionTypeFormatter" />


      <el-table-column prop="schedulingType[0]" :label="labelNames[0]" align="center"
                       :formatter="schedulingTypeDay1Formatter"/>
      <el-table-column prop="schedulingType[1]" :label="labelNames[1]" align="center"
                       :formatter="schedulingTypeDay2Formatter"/>
      <el-table-column prop="schedulingType[2]" :label="labelNames[2]" align="center"
                       :formatter="schedulingTypeDay3Formatter"/>
      <el-table-column prop="schedulingType[3]" :label="labelNames[3]" align="center"
                       :formatter="schedulingTypeDay4Formatter"/>
      <el-table-column prop="schedulingType[4]" :label="labelNames[4]" align="center"
                       :formatter="schedulingTypeDay5Formatter"/>
      <el-table-column prop="schedulingType[5]" :label="labelNames[5]" align="center"
                       :formatter="schedulingTypeDay6Formatter"/>
      <el-table-column prop="schedulingType[6]" :label="labelNames[6]" align="center"
                       :formatter="schedulingTypeDay7Formatter"/>
      <el-table-column width="80" label="操作" align="center">
        <template slot-scope="scope">
          <el-button
              type="text"
              icon="el-icon-edit"
              :disabled="editAble(scope.row)"
              size="mini"
              @click="editScheduling(scope.row.userId)">编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页内容-->

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNo"
        :page-sizes="[1,3,5,10]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <!-- 排班表格结束 -->

    <!-- 修改的弹出层开始 -->
    <el-dialog
        :title="title"
        :visible.sync="open"
        width="1200px"
        center
        append-to-body>
      <el-table :data="editData" border>
        <el-table-column prop="subsectionType" label="时间/日期" align="center" :formatter="subsectionTypeFormatter" />
        <el-table-column prop="schedulingType[0]" :label="labelNames[0]" align="center">
          <template slot-scope="scope">
            <el-select
                :disabled = "selAble(0)"
                v-model="scope.row.schedulingType[0]"
                clearable
                size="small">
              <el-option
                  v-for="d in schedulingTypeOptions"
                  :key="d.dictValue"
                  :label="d.dictLabel"
                  :value="d.dictValue"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="schedulingType[1]" :label="labelNames[1]" align="center">
          <template slot-scope="scope">
            <el-select
                :disabled = "selAble(1)"
                v-model="scope.row.schedulingType[1]"
                clearable
                size="small">
              <el-option
                  v-for="d in schedulingTypeOptions"
                  :key="d.dictValue"
                  :label="d.dictLabel"
                  :value="d.dictValue"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="schedulingType[2]" :label="labelNames[2]" align="center">
          <template slot-scope="scope">
            <el-select
                :disabled = "selAble(2)"
                v-model="scope.row.schedulingType[2]"
                clearable
                size="small">
              <el-option
                  v-for="d in schedulingTypeOptions"
                  :key="d.dictValue"
                  :label="d.dictLabel"
                  :value="d.dictValue"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="schedulingType[3]" :label="labelNames[3]" align="center">
          <template slot-scope="scope">
            <el-select
                :disabled = "selAble(3)"
                v-model="scope.row.schedulingType[3]"
                clearable
                size="small">
              <el-option
                  v-for="d in schedulingTypeOptions"
                  :key="d.dictValue"
                  :label="d.dictLabel"
                  :value="d.dictValue"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="schedulingType[4]" :label="labelNames[4]" align="center">
          <template slot-scope="scope">
            <el-select
                :disabled = "selAble(4)"
                v-model="scope.row.schedulingType[4]"
                clearable
                size="small">
              <el-option
                  v-for="d in schedulingTypeOptions"
                  :key="d.dictValue"
                  :label="d.dictLabel"
                  :value="d.dictValue"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="schedulingType[5]" :label="labelNames[5]" align="center">
          <template slot-scope="scope">
            <el-select
                :disabled = "selAble(5)"
                v-model="scope.row.schedulingType[5]"
                clearable
                size="small">
              <el-option
                  v-for="d in schedulingTypeOptions"
                  :key="d.dictValue"
                  :label="d.dictLabel"
                  :value="d.dictValue"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="schedulingType[6]" :label="labelNames[6]" align="center">
          <template slot-scope="scope">
            <el-select
                :disabled = "selAble(6)"
                v-model="scope.row.schedulingType[6]"
                clearable
                size="small">
              <el-option
                  v-for="d in schedulingTypeOptions"
                  :key="d.dictValue"
                  :label="d.dictLabel"
                  :value="d.dictValue"/>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 修改的弹出层结束 -->
  </div>
</template>
<script>
export default {
  name: "Schedule",
  data() {
    return {


      // 遮罩层
      loading: false,
      // 查询条件
      queryParams: {
        pageNo:1,
        pageSize:1,
        data:{},
        // deptId: "",
        // userId: "",
        // dateRange: [],

      },
      // 科室数据
      deptOptions: [],
      // 用户数据
      userOptions: [],
      schedulingData: {
        startTimeThisWeek: undefined,
        endTimeThisWeek: undefined
      },
      // 排班表的数据   应该从后台查询
      tableData: [],
      // 表头数据
      labelNames: ['', '', '', '', '', '', ''],
      // 弹出层的开启
      open: false,
      // 弹出层的标题
      title: '',
      // 弹出层里面的表格数据
      editData: [],
      schedulingTypeOptions: [],
      subsectionTypeOptions: [],


      paramsDate: new Date(), // 当前日期
      // 当前周的日期范围
      dateRange: [],
      dateRange2: [],
      total: 0,

      currentDate1: '', // 存储格式化后的当前日期
    }
  },
  created() {
    this.init();
  },
  computed: {
    groupNum() { // 获取医生列表数组
      return new Set(this.tableData.map(o => o.userId))
    }
  },
  methods: {

    updateDateAndWeekDay(daysToAdd = 0) {
      // 创建一个新的 Date 对象，代表当前时间或指定天数后的时间
      const now = new Date();
      const future = new Date(now);
      future.setDate(now.getDate() + daysToAdd);
      // 格式化日期
      const year = future.getFullYear();
      const month = String(future.getMonth() + 1).padStart(2, '0'); // 月份从0开始
      const day = String(future.getDate()).padStart(2, '0');
      // 获取星期几
      const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
      const weekDay = weekDays[future.getDay()];
      // 返回格式化的日期和星期几信息作为单个字符串
      return `${year}-${month}-${day} 星期${weekDay}`;
    },

    // 重置查询条件
    chongzhi() {
      // this.queryParams = {};
      // this.loadTable();
      //页面刷新
      location.reload();
    },
    init() {
      // 初始化科室名称
      this.$http.get("/hisRemoteDictData/getAllDept").then(res=>{
        this.deptOptions = res.data.data
      })
      // 初始化医生名称
      this.$http.get("/hisRemoteDictData/getAllSchedulingDoctor").then(res => {
        this.userOptions = res.data.data
      })
      // 查询班类型
      this.$http.get("/hisRemoteDictData/queryByDictType/his_scheduling_type").then(res => {
        // console.log(res.data.data)
        this.schedulingTypeOptions = res.data
        // console.log(this.schedulingTypeOptions)
      })
      // 查询排班时间段
      this.$http.get("/hisRemoteDictData/queryByDictType/his_subsection_type").then(res => {
        this.subsectionTypeOptions = res.data
        // console.log(this.subsectionTypeOptions)
      })
      this.currentWeek()
    },
    // 查询排班数据 和所有的 医生列表
    listScheduling() {
      this.loading = true
      // 调用API
      this.$http.post("/hisScheduling/queryByPage/",this.queryParams).then(res => {
        // this.labelNames = res.data.labelNames
        if (res.data.data.length === 0){
          this.$message.warning('未查询数据！！！')
        }else {
          this.tableData = res.data.data.list
          this.total = res.data.data.list[0].total
        }
        // this.schedulingData.startTimeThisWeek = res.data.beginDate
        // this.schedulingData.endTimeThisWeek = res.data.endDate
        this.loading = false
      })
    },

    //分页
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.listScheduling()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNo = val
      this.listScheduling()
    },

    // 查询
    handleQuery() {
      this.listScheduling()
    },
    // 重置
    resetQuery() {
      this.queryParams= {
        deptId: "",
        userId: "",
        dateRange: [],
        pageNo:1,
        pageSize:1
      }
      this.currentWeek()
      this.listScheduling()
    },

    // 上一周
    upWeek() {
      this.paramsDate = new Date(this.paramsDate.setDate(this.paramsDate.getDate() - 7))
      this.queryParams.dateRange = this.getWeekRange(this.paramsDate);
      this.listScheduling()
    },
// 当前周
    currentWeek() {
      this.paramsDate = new Date()
      this.queryParams.dateRange = this.getWeekRange(this.paramsDate);
      this.listScheduling()
    },
    // 下一周
    nextWeek() {
      this.paramsDate = new Date(this.paramsDate.setDate(this.paramsDate.getDate() + 7))
      this.queryParams.dateRange = this.getWeekRange(this.paramsDate);
      this.listScheduling()
    },

    getWeekRange(date) {
      // 获取指定日期所在周的周一和周日
      const day = date.getDay();
      // alert(day)
      const diffToMonday = day === 0 ? -6 : 1 - day;
      const monday = new Date(date);
      monday.setDate(date.getDate() + diffToMonday);
      const sunday = new Date(monday);
      sunday.setDate(monday.getDate() + 6);
      // console.log(sunday)
      const weekDates = [];
      let weekDates2 = [];
      for (let i = 0; i < 7; i++) {
        const currentDay = new Date(monday);
        currentDay.setDate(monday.getDate() + i);
        weekDates.push(this.formatDateXq(currentDay));
        weekDates2.push(this.formatDate(currentDay));
      }
      this.dateRange2 = weekDates2
      this.labelNames = weekDates

      this.schedulingData.startTimeThisWeek = this.formatDate(monday)
      this.schedulingData.endTimeThisWeek = this.formatDate(sunday)
      return [this.formatDate(monday),this.formatDate(sunday)];
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    formatDateXq(date) {
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const weekday = date.getDay();
      const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      return `${year}-${month}-${day}-${weekdays[weekday]}`;
    },



    // 合并的代码
    spanMethod(data) { // 对于表格数据进行分组合并操作，UI组件回调函数
      const {row, rowIndex, columnIndex} = data
      if (columnIndex < 2 || columnIndex > 9) { // 医生合并展示区
        const len = this.userGroup(row.userId)
        const lenName = this.userIdLen(row.userId)
        if (rowIndex === lenName) { // 某医生首位部门行
          return {
            rowspan: len,
            colspan: 1
          }
        } else {
          return { // 某医生非首位部门行
            rowspan: 0,
            colspan: 0
          }
        }
      } else { // 排班信息展示区
        return {
          rowspan: 1,
          colspan: 1
        }
      }
    },

    userGroup(name) { // 根据医生名称获取医生数量
      return this.tableData.filter(o => o.userId === name).length
    },
    userIdLen(name) { // 根据医生名称获取该医生第一个部门在全量部门中的偏移位置
      const tmp = Array.from(this.groupNum)
      const index = tmp.indexOf(name) // 某医生在全医生中的偏移位置
      let len = 0
      for (let i = 0; i < index; i++) {
        len += this.userGroup(tmp[i])
      }
      return len
    },


    // 翻译用户
    userFormatter(row) {
      let name = ''
      this.userOptions.filter(item => {
        if (parseInt(row.userId) === parseInt(item.userId)) {
          name = item.userName
        }
      })
      return name
    },
    // 翻译科室
    deptFormatter(row) {
      let name = ''
      this.deptOptions.filter(item => {
        if (parseInt(row.deptId) === parseInt(item.deptId)) {
          name = item.deptName
        }
      })
      return name
    },
    // 翻译排班时段
    subsectionTypeFormatter(row) {
      let subsectionTypeLabel;
      this.subsectionTypeOptions.forEach(item => {
        if (parseInt(item.dictValue) === parseInt(row.subsectionType)) {
          subsectionTypeLabel = item.dictLabel
        }
      })
      return subsectionTypeLabel;
    },

    selectDictLabel(data, value){
      let result;
      data.forEach(function(item){
        if (parseInt(item.dictValue) === parseInt(value)) {
          result =  item.dictLabel;
        }
      })
      return result;
    },
    // 翻译周一排班类型
    schedulingTypeDay1Formatter(row) {
      return this.selectDictLabel(this.schedulingTypeOptions, row.schedulingType[0])
    },
    // 翻译周二排班类型
    schedulingTypeDay2Formatter(row) {
      return this.selectDictLabel(this.schedulingTypeOptions, row.schedulingType[1])
    },
    // 翻译周三排班类型
    schedulingTypeDay3Formatter(row) {
      return this.selectDictLabel(this.schedulingTypeOptions, row.schedulingType[2])
    },
    // 翻译周四排班类型
    schedulingTypeDay4Formatter(row) {
      return this.selectDictLabel(this.schedulingTypeOptions, row.schedulingType[3])

    },
    // 翻译周五排班类型
    schedulingTypeDay5Formatter(row) {
      return this.selectDictLabel(this.schedulingTypeOptions, row.schedulingType[4])

    },
    // 翻译周六排班类型
    schedulingTypeDay6Formatter(row) {
      return this.selectDictLabel(this.schedulingTypeOptions, row.schedulingType[5])

    },
    // 翻译周7排班类型
    schedulingTypeDay7Formatter(row) {
      return this.selectDictLabel(this.schedulingTypeOptions, row.schedulingType[6])
    },


    // 打开编辑页面
    editScheduling(userId) {
      this.editData = []
      this.open = true
      let name = ''
      this.userOptions.filter(item => {
        if (parseInt(userId) === parseInt(item.userId)) {
          name = item.userName
        }
      })
      this.title = '修改【' + name + '】的排班信息'
      this.tableData.filter(item => {
        if (item.userId === userId) {
          this.editData.push(item)
        }
      })
    },
    // 关闭
    cancel() {
      this.open = false
    },
    // 保存
    handleSubmit() {
      let form = { beginDate: this.schedulingData.startTimeThisWeek, data: this.editData }
      this.loading = true
      // 保存
      this.loading = false
      this.$http.post("/hisScheduling/updateDoctorSchedulingMsg",form).then(res => {
        this.loading = false
        this.open = false
        this.$message.success('保存成功')
      }).catch(() => {
        this.loading = false
        this.$message.error('保存失败')
      })
    },
    // 根据时间 禁用编辑按钮
    editAble(){
      return this.schedulingData.endTimeThisWeek <= this.formatDate(new Date())
    },
    // 根据时间 禁用选择按钮
    selAble(a){
      return this.dateRange2[a] <= this.formatDate(new Date())
    },
  }
}
</script>
<style scoped>

</style>
